package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
//@Transactional mongodb的事务必须是复制集的方式
public class DestinationServiceImpl implements IDestinationService{
    //目的地的持久化
    @Autowired
    private DestinationRepository repository;

    //区域的持久化
    @Autowired
    private IRegionService regionService;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Destination destination) {
        destination.setId(null);//把id设置为null
        repository.save(destination);//存入destination对象

    }

    @Override
    public void update(Destination destination) {
        repository.save(destination);//编辑和保存是一样的,更新之后则要保存destination对象

    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public Destination get(String id) {
        //orEls,查询id,存在就返回,不承诺在就返回null
        return repository.findById(id).orElse(null);

    }

    @Override
    public List<Destination> list() {
        //查询所有
        return repository.findAll();
    }

    @Override
    public List<Destination> querygetDestByRegionId(String rid) {
        //通过区域id查询区域对象
        Region region = regionService.get(rid);
        //获取对象挂载的目的id集合
        List<String> ids = region.getRefIds();
        //通过id集合查询目的地集合
        return repository.findByIdIn(ids);
    }

    @Override
    public void saveOrUpdate(Destination destination) {
        //根据id进行查询,如果有就修改,没有就保存
        if (StringUtils.hasLength(destination.getId())){
            this.update(destination);
        }else {
            this.save(destination);
        }

    }

    //分页查询
    @Override
    public Page<Destination> query(DestinationQuery qo) {
        Query query = new Query();

        //关键字查询的搜索框
        if (StringUtils.hasLength(qo.getKeyword())){
            //regex因为使用is是不行的,
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }

        if (StringUtils.hasLength(qo.getParentId())){
            query.addCriteria(Criteria.where("parentId").regex(qo.getParentId()));

        }else {
            //为空的时候
            query.addCriteria(Criteria.where("parentId").is(null));

        }

//        另外加的

//        //查询总文档数
//        long totalCount = template.count(query, Destination.class);
//        //如果没有文档
//        if(totalCount == 0){
//            //返回空的页面结果集
//            return Page.empty();
//        }

        //创建分页和排序对象
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");

        return DBHelper.query(template,Destination.class,query,pageable);
    }

    //qo.getParentId 比如说找广州的id作为老爸
    @Override
    public List<Destination> queryToasts(String parentId) {

        ArrayList<Destination> list = new ArrayList<>();
        //吐司查询
        //循环
        //while(父对象为null)
        //递归
        this.createToast(list,parentId);
        Collections.reverse(list);//list集合的翻转  比如123,变成321
        return list;

    }


    //用于创建toast对象
    //中国 广东 广州
    private void createToast(ArrayList<Destination> list, String parentId) {
        //parentId 为null的时候不执行
        if (!StringUtils.hasLength(parentId)){
            return;
        }

        Destination destination = this.get(parentId);
        list.add(destination);
        if (StringUtils.hasLength(destination.getParentId())){
            createToast(list,destination.getParentId());
        }
    }


    /**
     * 1.查询挂载在区域之下的目的地
     * 2.通过区域id查询目的地
     * 3.实现该方法
     * @param regionId
     * @return
     */
    @Override
    public List<Destination> queryDestByRegionIdApi(String regionId) {
        List<Destination> list = new ArrayList<>();

        //第一层
        //区域:国内
        if ("-1".equals(regionId)){
            //查询中国下面所有的省份
            list = repository.findByParentName("中国");
        }else {
            //非国内
            list = this.querygetDestByRegionId(regionId);
        }
        
        
        //第二层
        for(Destination dest : list) {
            //repository ：目的地的持久化
            //利用父类的id去获取子类中所有的id,利用遍历的方式把它放在一个list集合中
//           List<Destination> children =  repository.findByParentId(dest.getId());
//           dest.setChildren(children);


            Pageable pageable =
                    PageRequest.of(0, 5, Sort.Direction.ASC, "_id");

            List<Destination> children =  repository.findByParentId(dest.getId(),pageable);
           dest.setChildren(children);



            
        }

        return list;
    }

}
